<template>
  <a-card title="修改密码" class="gi_page_card" :body-style="{ overflowY: 'auto' }">
    <a-space wrap :size="30">
      <a-form ref="formRef" :model="form" :rules="rules" auto-label-width class="update-password__form">
        <a-form-item label="原密码" field="oldPassword">
          <a-input-password v-model="form.oldPassword" placeholder="请输入原密码" allow-clear />
        </a-form-item>

        <a-form-item label="新密码" field="newPassword">
          <a-input-password v-model="form.newPassword" placeholder="请输入新密码" allow-clear />
          <template #extra>
            <a-typography-text type="secondary">
              密码长度为6-20位，必须包含小写字母、数字
            </a-typography-text>
          </template>
        </a-form-item>

        <a-form-item label="确认密码" field="password">
          <a-input-password v-model="form.password" placeholder="请再次输入新密码" allow-clear />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button @click="reset">重置</a-button>
            <a-button type="primary" @click="submit">确认修改</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-space>
  </a-card>
</template>

<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { updatePassword } from '@/apis/system/user'

defineOptions({ name: 'UpdatePassword' })

const form = reactive({
  oldPassword: '',
  newPassword: '',
  password: ''
})

// 密码强度校验规则
const validatePassword = (value: string, callback: (error?: string) => void) => {
  if (!value) {
    callback('请输入新密码')
    return
  }
  if (value.length < 6 || value.length > 20) {
    callback('密码长度为6-20位')
    return
  }
  // 必须包含小写字母
  if (!/[a-z]/.test(value)) {
    callback('密码必须包含小写字母')
    return
  }
  // 必须包含数字
  if (!/\d/.test(value)) {
    callback('密码必须包含数字')
    return
  }
  callback()
}

// 确认密码校验
const validateConfirmPassword = (value: string, callback: (error?: string) => void) => {
  if (!value) {
    callback('请再次输入新密码')
    return
  }
  if (value !== form.newPassword) {
    callback('两次输入的密码不一致')
    return
  }
  callback()
}

const rules: FormInstance['rules'] = {
  oldPassword: [
    { required: true, message: '请输入原密码' }
  ],
  newPassword: [
    { required: true, validator: validatePassword }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword }
  ]
}

const formRef = useTemplateRef('formRef')

const reset = () => {
  formRef.value?.resetFields()
}

const submit = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  // 这里调用修改密码的 API
  try {
    // TODO: 调用修改密码接口
    await updatePassword(form)
    Message.success('密码修改成功')
    reset()
  }
  catch (error) {
    Message.error('密码修改失败')
  }
}
</script>

<style lang="scss" scoped>
.update-password__form {
  max-width: 500px;
}

:deep(.vue-codemirror) {
  min-width: 300px;
}
</style>